//
//  NDContactTool.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/4.
//

import UIKit
import Contacts

class NDContactTool {
    static let shared = NDContactTool()
    private let store = CNContactStore()
    private let queue = DispatchQueue(label: "com.ndcontactmanager.queue", qos: .userInitiated)
    
    // MARK: - 权限管理
    func requestAccess(completion: @escaping (Bool) -> Void) {
        store.requestAccess(for: .contacts) { granted, error in
            DispatchQueue.main.async {
                let status = CNContactStore.authorizationStatus(for: .contacts)
                completion(status == .authorized && granted)
            }
        }
    }
    
    var authorizationStatus: CNAuthorizationStatus {
        return CNContactStore.authorizationStatus(for: .contacts)
    }
    
    // MARK: - 获取联系人
    func fetchAllContacts(completion: @escaping (Result<[CNContact], Error>) -> Void) {
        guard authorizationStatus == .authorized else {
            DispatchQueue.main.async {
                completion(.failure(NDContactError.unauthorized))
            }
            return
        }
        
        queue.async {
            do {
                let keys: [CNKeyDescriptor] = [
                    CNContactIdentifierKey,
                    CNContactGivenNameKey,
                    CNContactFamilyNameKey,
                    CNContactMiddleNameKey,
                    CNContactPhoneNumbersKey,
                    CNContactEmailAddressesKey,
                    CNContactOrganizationNameKey,
                    CNContactJobTitleKey,
                    CNContactThumbnailImageDataKey
                ].map { $0 as CNKeyDescriptor }
                
                let request = CNContactFetchRequest(keysToFetch: keys)
                request.sortOrder = .familyName
                
                var contacts = [CNContact]()
                try self.store.enumerateContacts(with: request) { contact, _ in
                    contacts.append(contact)
                }
                
                DispatchQueue.main.async {
                    completion(.success(contacts))
                }
            } catch {
                DispatchQueue.main.async {
                    completion(.failure(error))
                }
            }
        }
    }
    
    // MARK: - 联系人信息处理
    func formattedContactInfo(_ contact: CNContact) -> [String: Any] {
        let fullName: String
        if contact.familyName.isEmpty && contact.givenName.isEmpty {
            fullName = contact.organizationName.isEmpty ? "Unknown" : contact.organizationName
        } else {
            fullName = "\(contact.familyName)\(contact.givenName)"
        }
        
        let phoneNumbers = contact.phoneNumbers.map { $0.value.stringValue }.joined(separator: ",")
        
        return [
            "interestacle": fullName,
            "equhigh": phoneNumbers,
        ]
    }
    
    // MARK: - 搜索联系人
    func searchContacts(withName name: String, completion: @escaping (Result<[CNContact], Error>) -> Void) {
        guard authorizationStatus == .authorized else {
            completion(.failure(NDContactError.unauthorized))
            return
        }
        
        queue.async {
            do {
                let keys: [CNKeyDescriptor] = [
                    CNContactGivenNameKey,
                    CNContactFamilyNameKey,
                    CNContactPhoneNumbersKey
                ].map { $0 as CNKeyDescriptor }
                
                let predicate = CNContact.predicateForContacts(matchingName: name)
                let contacts = try self.store.unifiedContacts(matching: predicate, keysToFetch: keys)
                
                DispatchQueue.main.async {
                    completion(.success(contacts))
                }
            } catch {
                DispatchQueue.main.async {
                    completion(.failure(error))
                }
            }
        }
    }
    
    // MARK: - 根据标识符获取联系人
    func fetchContact(withIdentifier identifier: String, completion: @escaping (Result<CNContact, Error>) -> Void) {
        guard authorizationStatus == .authorized else {
            completion(.failure(NDContactError.unauthorized))
            return
        }
        
        queue.async {
            do {
                let keys: [CNKeyDescriptor] = [
                    CNContactGivenNameKey,
                    CNContactFamilyNameKey,
                    CNContactPhoneNumbersKey,
                    CNContactEmailAddressesKey
                ].map { $0 as CNKeyDescriptor }
                
                let contact = try self.store.unifiedContact(withIdentifier: identifier, keysToFetch: keys)
                
                DispatchQueue.main.async {
                    completion(.success(contact))
                }
            } catch {
                DispatchQueue.main.async {
                    completion(.failure(error))
                }
            }
        }
    }
}

// MARK: - 错误类型
enum NDContactError: LocalizedError {
    case unauthorized
    case contactNotFound
    
    var errorDescription: String? {
        switch self {
        case .unauthorized:
            return "没有通讯录访问权限"
        case .contactNotFound:
            return "未找到联系人"
        }
    }
}

// MARK: - 联系人扩展
extension CNContact {
    var displayName: String {
        if familyName.isEmpty && givenName.isEmpty {
            return organizationName.isEmpty ? "Unknown" : organizationName
        }
        return "\(familyName)\(givenName)"
    }
    
    var primaryPhoneNumber: String? {
        return phoneNumbers.first?.value.stringValue
    }
    
    var primaryEmail: String? {
        return emailAddresses.first?.value as String?
    }
}
